﻿/***************************************************
//  Copyright (c) Premium Tax Free 2011
***************************************************/

using System.Collections;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
using PremierTaxFree.PTFLib.Threading;

namespace PremierTaxFree.PTFLib.Data
{
    public class SQLWorker : CycleWorkerBase
    {
        private class CommandInfo
        {
            public SqlCommand Command { get; private set; }
            public bool Fire { get; private set; }
            public CommandInfo(SqlCommand comm, bool fire)
            {
                Command = comm;
                Fire = fire;
            }
        }

        private static SQLWorker instance = new SQLWorker();
        public static SQLWorker Default
        {
            get { return instance; }
        }

        private readonly object m_Lock = new object();
        private readonly Queue m_Queue = Queue.Synchronized(new Queue());
        public readonly AutoResetEvent Empty = new AutoResetEvent(false);

        ~SQLWorker()
        {
            Empty.Close();
        }

        public void Add(SqlCommand command, bool fire)
        {
            Debug.Assert(m_Worker != null, "Worker is not started");
            Debug.Assert(command != null);
            Debug.Assert(command.Connection != null);

            lock (m_Lock)
            {
                m_Queue.Enqueue(new CommandInfo(command, fire));
                Monitor.Pulse(m_Lock);
            }
        }

        protected override void ThreadFunction()
        {
            CommandInfo cmd = null;
            lock (m_Lock)
            {
                while (m_Queue.Count == 0)
                    Monitor.Wait(m_Lock);
            }
            cmd = (CommandInfo)m_Queue.Dequeue();

            if (m_Queue.Count == 0)
                Empty.Set();

            SQL.ExecuteNonQuery(cmd.Command, cmd.Fire);

        }
    }    
}
